import type { WorkflowChatRequest, WorkflowChatResponse, WorkflowConversation, WorkflowHistoryMessage } from './workflowTypes';
import { apiService } from '@/config/api';

// 工作流API服务类 - 简洁统一模式
export class WorkflowApiService {
  // 发送对话消息
  async sendMessage(data: WorkflowChatRequest): Promise<WorkflowChatResponse> {
    try {
      if (data.response_mode === 'streaming') {
        // 流式响应返回response对象
        return await apiService.postStream('/chat-messages', data) as any;
      }
      else {
        // 阻塞响应返回JSON数据
        return await apiService.post('/chat-messages', data);
      }
    }
    catch (error) {
      console.error('发送工作流消息失败:', error);
      throw error;
    }
  }

  // 停止指定task的生成
  async stopMessage(taskId: string, user: string): Promise<{ result: string } | undefined> {
    try {
      return await apiService.post(`/chat-messages/${taskId}/stop`, { user });
    }
    catch (error) {
      console.error('停止响应失败:', error);
      return undefined;
    }
  }

  // 流式发送消息
  async sendMessageStream(
    data: WorkflowChatRequest,
    onChunk: (chunk: any) => void,
    onError?: (error: any) => void,
  ): Promise<void> {
    try {
      const response = await this.sendMessage({
        ...data,
        response_mode: 'streaming',
      });

      if (response instanceof Response) {
        const reader = response.body?.getReader();
        const decoder = new TextDecoder();

        if (!reader) {
          throw new Error('无法获取响应流');
        }

        let accumulatedContent = '';

        while (true) {
          const { done, value } = await reader.read();

          if (done)
            break;

          const chunk = decoder.decode(value);
          const lines = chunk.split('\n');

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.slice(6));

                // 累积内容
                if (data.answer) {
                  accumulatedContent += data.answer;
                  onChunk({
                    ...data,
                    answer: accumulatedContent,
                  });
                }
                else {
                  onChunk(data);
                }
              }
              catch {
                // 忽略解析错误
              }
            }
          }
        }
      }
    }
    catch (error) {
      console.error('流式发送消息失败:', error);
      onError?.(error);
    }
  }

  // 获取会话列表
  async getConversations(params: { user: string; last_id?: string; limit?: number }): Promise<WorkflowConversation[]> {
    const data = await apiService.get('/conversations', params);
    return data?.data || [];
  }

  // 获取会话消息历史
  async getMessages(params: { user: string; conversation_id: string; last_id?: string; limit?: number }): Promise<WorkflowHistoryMessage[]> {
    const data = await apiService.get('/messages', params);
    return data?.data || [];
  }

  // 上传文件
  async uploadFile(file: File, user: string): Promise<{ id: string; url?: string; name?: string; size?: number; extension?: string; mime_type?: string; created_at?: number }> {
    const form = new FormData();
    form.append('file', file);
    form.append('user', user);
    return await apiService.post('/files/upload', form, 'multipart/form-data');
  }
}

// 创建工作流API服务实例
export const workflowApiService = new WorkflowApiService();

// 兼容性导出（保持原有接口不变）
export const sendWorkflowMessage = (data: WorkflowChatRequest) => workflowApiService.sendMessage(data);
export const sendWorkflowMessageStream = (data: WorkflowChatRequest, onChunk: any, onError?: any) => workflowApiService.sendMessageStream(data, onChunk, onError);
export const stopWorkflowMessage = (taskId: string, user: string) => workflowApiService.stopMessage(taskId, user);
export const getWorkflowConversations = (params: any) => workflowApiService.getConversations(params);
export const getWorkflowMessages = (params: any) => workflowApiService.getMessages(params);
export const uploadWorkflowFile = (file: File, user: string) => workflowApiService.uploadFile(file, user);
